<template>
  <div class="register-container">
    <div class="register-card">
      <h2>用户注册</h2>
      <el-form 
        ref="registerForm" 
        :model="form" 
        :rules="rules" 
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            @blur="checkUsername"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            placeholder="请输入邮箱" 
            prefix-icon="Message"
            @blur="checkEmail"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            :loading="loading" 
            block
          >
            注册
          </el-button>
        </el-form-item>
        
        <div class="login-link">
          已有账号? <router-link to="/login/user">立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();
const registerForm = ref(null);
const loading = ref(false);

const form = ref({
  username: '',
  password: '',
  email: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};
const checkUsername = async () => {
  if (!form.value.username) return;
  
  try {
    const res = await axios.get(`/api/auth/check-username?username=${form.value.username}`);
    if (res.data.exists) {
      registerForm.value.validateField('username', () => {
        ElMessage.error('用户名已存在');
      });
    }
  } catch (error) {
    console.error('检查用户名失败:', error);
  }
};

const checkEmail = async () => {
  if (!form.value.email) return;
  
  try {
    const res = await axios.get(`/api/auth/check-email?email=${form.value.email}`);
    if (res.data.exists) {
      registerForm.value.validateField('email', () => {
        ElMessage.error('邮箱已注册');
      });
    }
  } catch (error) {
    console.error('检查邮箱失败:', error);
  }
};

// 移除checkUsername方法
const handleRegister = async () => {
  try {
    loading.value = true;
    await registerForm.value.validate();
    
    const response = await axios.post('/api/auth/register', form.value);
    
    if (response.data.code === 200) {
      ElMessage.success('注册成功');
      router.push('/login/user');
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    if (error.response) {
      // 显示后端返回的具体错误信息
      const msg = error.response.data.message || 
                 (error.response.data.code === 400 ? '用户名或邮箱已存在' : '注册失败');
      ElMessage.error(msg);
    } else {
      ElMessage.error('网络错误：' + error.message);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-card h2 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.login-link {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}
</style>